package com.example.demo04plc.plc.common;

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.function.BiConsumer;

@Slf4j
public abstract class AbstractPlcConnection implements PlcConnection {

    @Getter
    private final String deviceId;
    private ScheduledFuture<?> scheduledFuture;

    public AbstractPlcConnection(String deviceId) {
        this.deviceId = deviceId;
    }


    @Override
    public void scheduleRead(ScheduledExecutorService scheduledExecutorService, PlcReadRequest plcReadRequest, BiConsumer<String, PlcReadResponse> consumer, long initialDelay, long period, TimeUnit unit) {
        this.closeScheduleRead();
        log.info("设备[{}]开始读取的定时任务", deviceId);
        this.scheduledFuture = scheduledExecutorService.scheduleAtFixedRate(() -> {
            PlcReadResponse readResponse = this.read(plcReadRequest);
            consumer.accept(deviceId, readResponse);
        }, initialDelay, period, unit);
    }
    @Override
    public void closeScheduleRead() {
        if (scheduledFuture != null) {
            log.info("设备[{}]关闭读取的定时任务", deviceId);
            scheduledFuture.cancel(true);
        }
    }

}
